package com.java46.front.base.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @ClassName: EncodingFilter
 * @Description: 处理编码异常
 * @author: zuxia
 * @date: 2018年7月4日 下午2:50:52
 */
public class EncodingFilter implements Filter {

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) resp;
		// 请求的方法： get|post
		String method = request.getMethod();
		if ("GET".equalsIgnoreCase(method)) {
			//处理get请求的编码异常
			request = new HttpServletRequestWrapper(request);
		} else {
			request.setCharacterEncoding("UTF-8");
		}
		response.setCharacterEncoding("UTF-8");
		chain.doFilter(request, response);
	}

	@Override
	public void destroy() {
	}

}
